//
//  LGPrescriptionChartView.m
//  BreathTrainingTool
//
//  Created by 1234 on 2025/1/7.
//

#import "LGPrescriptionChartView.h"
#import "LGScrollView.h"
#define topMargin    viewPix(45)

#define leftMargin   viewPix(45)+iPadMargin(10)

#define lineHeight   viewPix(25)

#define scrollWidth   (Screen_W - viewPix(95))

#define scrollHeight  (lineHeight*5 + viewPix(60))

@interface LGPrescriptionChartView()<UIScrollViewDelegate>
/**   */
@property (nonatomic , strong)LGScrollView *scrollView;
/**   */
@property (nonatomic , strong)NSMutableArray *yaxisArray;
/**   */
@property (nonatomic , strong)NSMutableArray *dayArray;
/**   */
@property (nonatomic , strong)NSMutableArray *buttonArray;
/**   */
@property (nonatomic , strong)NSMutableArray *layerArray;
/**   */
@property (nonatomic , strong)UIButton *leftButton;
/**   */
@property (nonatomic , strong)UIButton *rightButton;
/**   */
@property (nonatomic , strong)NSArray *highArray;
/**   */
@property (nonatomic , strong)NSArray *lowArray;
/**   */
@property (nonatomic , assign)NSInteger totalCount;
/**   */
@property (nonatomic , assign)CGFloat itemWidth;

@end

@implementation LGPrescriptionChartView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.itemWidth = scrollWidth/5.0;
        self.backgroundColor = [UIColor whiteColor];
        self.cornerRidus = 20;
        [self addSubview:self.titleLabel];
        [self addSubview:self.scrollView];
    }
    return self;
}

-(void)setDataArray:(NSArray *)dataArray{
    _dataArray = dataArray;
    //创建Y轴
    CGFloat segment = [self creatYaxisWithArray:dataArray];
    
    self.totalCount = dataArray.count>0?dataArray.count:1;
    NSInteger count = (self.totalCount>5)?5:self.totalCount;
    self.itemWidth = scrollWidth/count;
    CGFloat totalWidth = viewPix(20)+self.itemWidth*self.totalCount;
    self.scrollView.contentSize = CGSizeMake(totalWidth, scrollHeight);
    [self.scrollView setContentOffset:CGPointMake(totalWidth-scrollWidth-viewPix(10), 0)];
    
    for (UILabel *label in self.dayArray) {
        [label removeFromSuperview];
    }
    
    for (UIButton *button in self.buttonArray) {
        [button removeFromSuperview];
    }
    
    for (CAShapeLayer *layer in self.layerArray) {
        [layer removeFromSuperlayer];
    }
    [self.dayArray removeAllObjects];
    [self.buttonArray removeAllObjects];
    [self.layerArray removeAllObjects];
    
    NSMutableArray *dayArray = [NSMutableArray array];
    NSMutableArray *pointArray = [NSMutableArray array];
    NSMutableArray *pointArray2 = [NSMutableArray array];
    for (NSInteger i=0; i<dataArray.count; i++){
        NSDictionary *tempDic = dataArray[i];
        //创建X轴
        NSString *dayString = [LGNSString(tempDic[@"date"]) stringByReplacingOccurrencesOfString:@"-" withString:@"/"];
        UILabel *dayLabel = [UILabel lableWithText:dayString colorString:@"#928F94" textFont:LGFont(11) textAlignment:NSTextAlignmentCenter lines:1];
        dayLabel.frame = CGRectMake(viewPix(5)+self.itemWidth*i, lineHeight*5+viewPix(3), self.itemWidth+viewPix(5), lineHeight);
        dayLabel.transform = CGAffineTransformRotate(dayLabel.transform, -M_PI_4);
        [self.scrollView addSubview:dayLabel];
        [dayArray addObject:dayLabel];
        
        //创建点
        CGFloat pointY1 = scrollHeight-([tempDic[@"num"] floatValue]/segment*lineHeight+viewPix(60)+lineHeight*0.5);
        UIButton *button1 = [UIButton buttonWithImage:@"体征数据-紫色" selectImage:@"体征数据-紫色"];
        button1.bounds = CGRectMake(0, 0, viewPix(20), viewPix(20));
        button1.center = CGPointMake(viewPix(10)+self.itemWidth/2.0+self.itemWidth*i, pointY1);
        button1.tag = 1000+i;
        [button1 addTarget:self action:@selector(pointButtonTouch:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView addSubview:button1];
        [self.buttonArray addObject:button1];
        NSValue *point1 = [NSValue valueWithCGPoint:button1.center];
        [pointArray addObject:point1];
    }
    [self drawCurveLine:pointArray lineColor:@"#796DF5"];
    [self drawCurveLine:pointArray2 lineColor:@"#198EFD"];
    self.dayArray = dayArray;
}

-(void)pointButtonTouch:(UIButton *)sender{
    NSInteger index = sender.tag%1000;
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:1000+i];
        button.selected = (index == i)?YES:NO;
    }
    CGPoint point = [self.scrollView convertPoint:sender.center toView:self.superview];
    NSLog(@">>>???>>>%f--%f",point.x,point.y);
    NSString *score = [NSString stringWithFormat:@"%@ %@",self.dataArray[index][@"num"],self.unit];
    NSDictionary *tempDic = @{@"title":@"",@"score":score,@"status":@""};
    if(self.delegate && [self.delegate respondsToSelector:@selector(showAlertView:date:point:)]){
        [self.delegate showAlertView:@[tempDic] date:LGNSString(self.dataArray[index][@"date"]) point:point];
    }
}


//创建Y轴
-(CGFloat)creatYaxisWithArray:(NSArray *)dataArray{
    NSInteger maxValue = 4;
    for (NSDictionary *tempDic in dataArray) {
        NSInteger value = ceil([LGNSString(tempDic[@"num"]) floatValue]);
        maxValue = (value>maxValue)?value:maxValue;
    }
    maxValue = (maxValue%4==0) ? maxValue : (maxValue/4 + 1)*4;
    NSMutableArray *titleArray = [NSMutableArray array];
    CGFloat segment = maxValue/4.0;
    for (NSInteger i=0; i<5; i++) {
        [titleArray addObject:[NSString stringWithFormat:@"%.0f",maxValue-segment*i]];
    }

    
    for (UIView *view in self.yaxisArray) {
        [view removeFromSuperview];
    }
    [self.yaxisArray removeAllObjects];
    
    for (NSInteger i=0; i<titleArray.count; i++) {
        //Y轴标题
        UILabel *label = [UILabel lableWithText:titleArray[i] colorString:@"#333333" textFont:LGFont(12) textAlignment:NSTextAlignmentCenter lines:1];
        label.frame = CGRectMake(viewPix(5), topMargin+lineHeight*i, leftMargin-5, lineHeight);
        [self addSubview:label];
        //虚线
        LGDottedLineView *lineView = [[LGDottedLineView alloc]initWithFrame:CGRectMake(0, lineHeight*i, self.itemWidth*30+viewPix(50), lineHeight)];
        [self.scrollView addSubview:lineView];
        
        [self.yaxisArray addObject:label];
        [self.yaxisArray addObject:lineView];
    }
    return segment;
}

//画线
-(void)drawCurveLine:(NSArray *)arry lineColor:(NSString *)color{
    if(arry.count == 0) return;
    CGPoint startPoint = [[arry objectAtIndex:0] CGPointValue];
    CGPoint lastPoint;
    UIBezierPath *lineBeizer = [UIBezierPath bezierPath];
    [lineBeizer setLineWidth:2.0];
    [lineBeizer moveToPoint:startPoint];

    for (NSInteger i = 0;i < arry.count;i++ ) {
        if (i <arry.count-1 ) {
            CGPoint nowPoint = [[arry objectAtIndex:i] CGPointValue];
            CGPoint futPoint  = [[arry objectAtIndex:i+1] CGPointValue];
            [lineBeizer addCurveToPoint:futPoint controlPoint1:CGPointMake((nowPoint.x+futPoint.x)/2, nowPoint.y) controlPoint2:CGPointMake((nowPoint.x+futPoint.x)/2, futPoint.y)];
            if (i == arry.count-2) {
                [lineBeizer moveToPoint:futPoint];//添加连线
                lastPoint = futPoint;
            }
        }
    }
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = lineBeizer.CGPath;
    shapeLayer.fillColor = [UIColor clearColor].CGColor;
    shapeLayer.strokeColor = [UIColor colorWithString:color].CGColor;
    shapeLayer.lineWidth = 2.0;
    [self.scrollView.layer addSublayer:shapeLayer];
    [self.layerArray addObject:shapeLayer];
    for(NSInteger i=0; i<self.totalCount; i++){
        UIButton *button = [self viewWithTag:1000+i];
        UIButton *button2 = [self viewWithTag:2000+i];
        [self.scrollView bringSubviewToFront:button];
        [self.scrollView bringSubviewToFront:button2];
    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (self.delegate && [self.delegate respondsToSelector:@selector(hiddenAlertView)]) {
        [self.delegate hiddenAlertView];
    }
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"血压" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightMedium) textAlignment:NSTextAlignmentLeft lines:1];
        _titleLabel.frame = CGRectMake(viewPix(16), viewPix(16), viewPix(200), viewPix(23));
    }
    return _titleLabel;
}

-(LGScrollView *)scrollView{
    if(!_scrollView){
        _scrollView = [[LGScrollView alloc] initWithFrame:CGRectMake(leftMargin, topMargin, scrollWidth, scrollHeight)];
        _scrollView.contentSize = CGSizeMake(self.itemWidth*30+viewPix(20), scrollHeight);
        _scrollView.showsHorizontalScrollIndicator = NO;
        _scrollView.delegate = self;
    }
    return _scrollView;
}

-(NSMutableArray *)yaxisArray{
    if(!_yaxisArray){
        _yaxisArray = [NSMutableArray array];
    }
    return _yaxisArray;
}

-(NSMutableArray *)dayArray{
    if(!_dayArray){
        _dayArray = [NSMutableArray array];
    }
    return _dayArray;
}

-(NSMutableArray *)buttonArray{
    if(!_buttonArray){
        _buttonArray = [NSMutableArray array];
    }
    return _buttonArray;
}

-(NSMutableArray *)layerArray{
    if(!_layerArray){
        _layerArray = [NSMutableArray array];
    }
    return _layerArray;
}

@end
